package xin.zhiyin.工具.阿里云OSS;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.web.multipart.MultipartFile;
import xin.zhiyin.实体.阿里云OSS配置信息Entity;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class 阿里云OSSUtil {
    private String ACCESS_KEY_ID ;  /*KeyId*/
    private String ACCESS_KEY_SECRET ;  /*KeySecret*/
    private String END_POINT ;  /*END_POINT*/
    private String BUCKET_NAME;  // OSS存储桶名称
    public 阿里云OSSUtil(阿里云OSS配置信息Entity 阿里云OSS)
    {
        this.ACCESS_KEY_ID = 阿里云OSS.getKeyId();
        this.ACCESS_KEY_SECRET = 阿里云OSS.getKeySecret();
        this.END_POINT = 阿里云OSS.getEndPoint();
        this.BUCKET_NAME = 阿里云OSS.getBucketName();
    }
    /*根据路径获取文件扩展名（不包含.）*/
    public String 获取文件扩展名(String 文件路径)
    {
        File file = new File(文件路径);
        String fileName = file.getName();
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }
    /**
     * 获取文件扩展名
     * 内容类型转媒体类型
     *
     * @param contentType
     * @return
     */
    public String getMediaType(String contentType) {
        String fileExtension = null;
        switch (contentType) {
            case "image/bmp":
                fileExtension = ".bmp";
                break;
            case "image/gif":
                fileExtension = ".gif";
                break;
            case "image/jpeg":
                fileExtension = ".jpeg";
                break;
            case "video/mp4":
                fileExtension = ".mp4";
                break;
        }
        // 默认返回类型
        return fileExtension;

    }
    /**
     * 获取内容类型
     * 媒体类型转内容类型
     *
     * @param fileExtension
     * @return
     */
    public String getContentType(String fileExtension){
        String contentType = null;
        switch (fileExtension) {
            case ".bmp":
                contentType = "image/bmp";
                break;
            case ".gif":
                contentType = "image/gif";
                break;
            case ".jpeg":
                contentType = "image/jpeg";
                break;
            case ".mp4":
                contentType = "video/mp4";
                break;
        }
        // 默认返回类型
        return contentType;
    }
    public String 上传文件(MultipartFile file){
        OSS ossClient = new OSSClientBuilder().build(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);  /*创建OSSClient实例,要放在方法中否则会报错：Unable to execute HTTP request: Connection pool shut down Caught an ClientException, which means the client encountered a serious internal problem while trying to communicate with OSS, such as not being able to access the network.*/

        String 类型目录 = null ;
        try {
            String fileName = 获取文件扩展名(file.getOriginalFilename());
            if(fileName.equalsIgnoreCase("png") | fileName.equalsIgnoreCase("jpg") | fileName.equalsIgnoreCase("gif"))  /*equalsIgnoreCase:不区分大小写;equals:区分大小写*/
            {
                类型目录 = "880/images/";
            } else if (fileName.equalsIgnoreCase("mp4")) {
                类型目录 = "880/videos/";
            }

            String uuid = UUID.randomUUID().toString().replaceAll("-", "");  /*生成随机唯一的识别码*/
            fileName = uuid +"." + fileName;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");  /*把文件按照日期进行分类;获取当前日期,格式化*/
            String datePath = sdf.format(new Date());
            fileName = 类型目录 + datePath + "/" + fileName;  /*拼接*/

            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, fileName, new ByteArrayInputStream(file.getBytes()));  /*创建PutObjectRequest对象*/
            ossClient.putObject(putObjectRequest);  /*上传文件*/
            ossClient.shutdown();  /*关闭OSSClient*/
            // 把上传之后文件路径返回，需要把上传到阿里云oss路径手动拼接出来
            //https://zhi-server.oss-cn-nanjing.aliyuncs.com/images/2023/09/26/261fc5176e7740f7bc2a2fcc62eb4f51.png
//            return "https://" + BUCKET_NAME + "." + END_POINT + "/" + fileName;
            return "http://" + "image.880.xin/" + fileName;
        } catch (Exception e) {
            System.out.println("文件上传失败：" + e.getMessage());
            return "";
        }
    }
    public void 删除文件(String url)
    {
        OSS ossClient = new OSSClientBuilder().build(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);  /*创建OSSClient实例,要放在方法中否则会报错：Unable to execute HTTP request: Connection pool shut down Caught an ClientException, which means the client encountered a serious internal problem while trying to communicate with OSS, such as not being able to access the network.*/
        String host = "https://" + BUCKET_NAME + "." + END_POINT + "/";
        String objectName = url.substring(host.length());
        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(BUCKET_NAME,objectName);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
